from django import template
from django.db.models import Count
from django.core.paginator import Paginator
from ..models import *

register = template.Library()
per_page = 5

@register.simple_tag
def get_category_list():
    return Category.objects.annotate(total_num=Count('article')).filter(total_num__gt=0)

@register.simple_tag
def get_tag_list():
    return Tag.objects.annotate(total_num=Count('article')).filter(total_num__gt=0)

@register.inclusion_tag('blog/articles.html',  takes_context=True)
def show_article_list(context):
    request = context['request']
    sort_by = request.GET.get('sort_by')
    if 'category' in context:
        article_list = context['category'].article_set.all()
    elif 'tag' in context:
        article_list = context['tag'].article_set.all()
    else:
        article_list = Article.objects.all()

    if sort_by:
        article_list = article_list.order_by(sort_by)
    else:
        article_list = article_list.order_by('-id')

    paginator = Paginator(article_list, per_page)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    return {'page_obj': page_obj}
